#include "stdafx.h"
#include "ui/poke_hotkey_fetcher.h"
#include "poke_framework.h"
#include "models/atom_interface/ai_hotkey_manager.h"
#include "base/window/window_utils.h"

IMPLEMENT_DYNAMIC(CPokeHotkeyFetcher, CHotKeyCtrl)

CPokeHotkeyFetcher::CPokeHotkeyFetcher()
    : m_nHotkeyId(0)
    , m_nKeyDownNum(0)
{

}

CPokeHotkeyFetcher::~CPokeHotkeyFetcher()
{

}

void CPokeHotkeyFetcher::ResetOption(int nHotkeyId)
{
    m_nHotkeyId = nHotkeyId;
    m_nKeyDownNum = 0;
}

void CPokeHotkeyFetcher::EndFetch(BOOL bSave)
{
    if(bSave) {
        WORD nVirtualKeyCode = 0;
        WORD nModifiers = 0;
        GetHotKey(nVirtualKeyCode, nModifiers);

        if(0 != nModifiers && 0 != nVirtualKeyCode) {
            PokeHotkeyKey oNewHotkey;
            oNewHotkey.m_nKey = nVirtualKeyCode;
            oNewHotkey.m_nModifier = MfcHotkeyModifierToSysHotkeyModifier(nModifiers);
            PokeFramework::get()->Execute(PAN_HOTKEY_MANAGER, PFI_PUBLISH_HOTKEY, (void *)(LONG_PTR)m_nHotkeyId, &oNewHotkey);
            PokeFramework::get()->FireEvent(PEI_UPDATE_HOTKEY_UI, NULL);
        }
    }

    ResetOption(0);

    DestroyWindow();
}

BEGIN_MESSAGE_MAP(CPokeHotkeyFetcher, CHotKeyCtrl)
    ON_WM_KILLFOCUS()
    ON_WM_KEYDOWN()
    ON_WM_KEYUP()
    ON_WM_SYSKEYDOWN()
    ON_WM_SYSKEYUP()
END_MESSAGE_MAP()

void CPokeHotkeyFetcher::OnKillFocus(CWnd* pNewWnd)
{
    CHotKeyCtrl::OnKillFocus(pNewWnd);

    // TODO: Add your message handler code here
    EndFetch(FALSE);
}

void CPokeHotkeyFetcher::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default
    if((nFlags & 0x4000) == 0) {
        ++m_nKeyDownNum;
    }

    CHotKeyCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
}

void CPokeHotkeyFetcher::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default
    --m_nKeyDownNum;

    if(0 == m_nKeyDownNum) {
        EndFetch(TRUE);
    }

    CHotKeyCtrl::OnKeyUp(nChar, nRepCnt, nFlags);
}

void CPokeHotkeyFetcher::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default
    if((nFlags & 0x4000) == 0) {
        ++m_nKeyDownNum;
    }

    CHotKeyCtrl::OnSysKeyDown(nChar, nRepCnt, nFlags);
}

void CPokeHotkeyFetcher::OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default
    --m_nKeyDownNum;

    if(0 == m_nKeyDownNum) {
        EndFetch(TRUE);
    }

    CHotKeyCtrl::OnSysKeyUp(nChar, nRepCnt, nFlags);
}
